package com.ifcar.app.activity;

import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.activity.R;

import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebStorage.QuotaUpdater;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class LinkOutSide extends BaseActivity  {
    
    private WebView contentWebview;
    private LinearLayout loadingbar;
    private String href = "http://3g.163.com/x/";
    private CookieManager cookieManager;
    private String host = "";
    private RelativeLayout top_space;
    private boolean needDirectBack = false;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.linkoutside);
        findViewsById();
        Cookie();
        setListener();
        Bundle bundle = this.getIntent().getExtras();
        if(null!=bundle){
            href =  bundle.getString("href");
            //href = "http://go.2012.163.com/t?nonav";
            host = Tools.getHost(href);
        }
        if(null!=href && href.endsWith("go.2012.163.com/t?nonav")){
            top_space.setVisibility(View.GONE);
            needDirectBack = true;
        }
        new Thread() {
            public void run() {
                handler.sendEmptyMessage(0); 
            }
        }.start();
    }
    
    /**
     * 设置webview的cookie
     */
    private void Cookie(){
        
        cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
    }
    
    private void findViewsById() {
        top_space = (RelativeLayout)findViewById(R.id.top_space);
        contentWebview = (WebView)findViewById(R.id.contentWebview);
        loadingbar = (LinearLayout) findViewById(R.id.contentloadingbar);
        loadingbar.setVisibility(View.VISIBLE);
        contentWebview.getSettings().setJavaScriptEnabled(true);
        contentWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//        if (android.os.Build.VERSION.SDK_INT >= 5) {
//            contentWebview.getSettings().setDatabaseEnabled(false);
//        }
        contentWebview.getSettings().setSaveFormData(true);
        contentWebview.getSettings().setSavePassword(true);
//        contentWebview.clearCache(true);
        contentWebview.getSettings().setBuiltInZoomControls(true);
        contentWebview.getSettings().setAllowFileAccess(true);
        contentWebview.getSettings().setUseWideViewPort(true);
//        contentWebview.getSettings().setAllowContentAccess(true);
 //       contentWebview.getSettings().setEnableSmoothTransition(true);
        String host = Tools.getHostbyWAP(this);
        if(null!=host){
            contentWebview.enablePlatformNotifications();
            contentWebview.setHttpAuthUsernamePassword(host,"80","","");
        }
        
     }
    
    private void setListener(){
        
        contentWebview.setWebChromeClient(new MyWebChromeClient());
        
        contentWebview.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                    String mimetype, long contentLength) {
                // 实现下载的代码
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        
        contentWebview.setWebViewClient(new WebViewClient(){
            
            @Override
            public void onPageFinished(WebView view, String url) {
                loadingbar.setVisibility(View.GONE);
                super.onPageFinished(view, url);
                if(null!=host && !"".equalsIgnoreCase(host)){
                    String ck = cookieManager.getCookie(host);
                    cookieManager.setCookie(host, ck);
                    CookieSyncManager.createInstance(LinkOutSide.this);
                    CookieSyncManager.getInstance().sync();
                }
            }

            public void onReceivedSslError(WebView view,
                    SslErrorHandler handler, SslError error) {
                // TODO Auto-generated method stub
                try {
                    if(handler != null)
                    handler.proceed();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(url.equals("close://")){
                    LinkOutSide.this.finish();
                    return true;
                }else{
                    view.loadUrl(url);
                    return true;
                }
               
            }
        });
        
        
    }
    
    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;

    /** 
     * 监控文件选择 
     *
     * 
     */  
    class MyWebChromeClient extends WebChromeClient {  
        // The undocumented magic method override  
        // Eclipse will swear at you if you try to put @Override here  
        
        // Android 3.0- 以下使用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {  
   
            mUploadMessage = uploadMsg;  
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
            i.addCategory(Intent.CATEGORY_OPENABLE);  
            i.setType("image/*");  
            LinkOutSide.this.startActivityForResult(  
                    Intent.createChooser(i, "Image Browser"),  
                    FILECHOOSER_RESULTCODE);  
        }
     // Android 3.0+ 使用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;  
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
            i.addCategory(Intent.CATEGORY_OPENABLE);  
            i.setType("image/*");  
            LinkOutSide.this.startActivityForResult(  
                    Intent.createChooser(i, "Image Browser"),  
                    FILECHOOSER_RESULTCODE);  
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // TODO Auto-generated method stub
            super.onProgressChanged(view, newProgress);
            
            if(newProgress>=100){
                loadingbar.setVisibility(View.GONE);
                if(null!=host && !"".equalsIgnoreCase(host)){
                    String ck = cookieManager.getCookie(host);
                    cookieManager.setCookie(host, ck);
                    CookieSyncManager.createInstance(LinkOutSide.this);
                    CookieSyncManager.getInstance().sync();
                } 
            }
            
        }

        @Override
        public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,
                QuotaUpdater quotaUpdater) {
            // TODO Auto-generated method stub
            super.onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota, quotaUpdater);
        }  
        
        
    }  
    /**  
     * 返回文件选择  
     */  
    @Override  
    protected void onActivityResult(int requestCode, int resultCode,  
            Intent intent) {  
        if (requestCode == FILECHOOSER_RESULTCODE) {  
            if (null == mUploadMessage)  
                return;  
            Uri result = intent == null || resultCode != RESULT_OK ? null  
                    : intent.getData();  
            mUploadMessage.onReceiveValue(result);  
            mUploadMessage = null;  
       
        }  
    }  

    
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            
            
            
            switch (msg.what) {
            case 0:
                contentWebview.loadUrl(href);
                break;
            }
        }
    };
    
    public void goBackClick(View view){
		finish();
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        
        if (!needDirectBack && null!=contentWebview 
                && contentWebview.canGoBack() 
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK 
                && event.getRepeatCount() == 0 
                ) {  
            contentWebview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    public void onApplyTheme() {
        super.onApplyTheme();
        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        themeSettingsHelper.setViewBackgroud(this, R.id.top_space, R.drawable.top_background);
        themeSettingsHelper.setImageViewSrc(this, R.id.top_id_image, R.drawable.netease_top);
        themeSettingsHelper.setTextViewColor(this, R.id.top_txt, R.color.main_title_color);
      //返回夜间模式
        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_from_comment, R.drawable.go_back);
    }

}
